<template>
  <div class="data-source-container p-4">
    <!-- 页面标题 -->
    <div class="page-header flex justify-between items-center mb-5">
      <div>
        <h2 class="text-2xl font-bold mb-1 flex items-center">
          <div class="i-carbon-data-base text-primary mr-2 text-3xl"></div>
          数据源管理
        </h2>
        <p class="text-gray-500 text-sm">管理所有接入数据中台的外部系统数据源</p>
      </div>
      <el-button type="primary" @click="handleAdd" class="flex items-center">
        <div class="i-carbon-add mr-1"></div>注册数据源
      </el-button>
    </div>

    <!-- 搜索条件区 -->
    <el-card class="mb-4 border-0 shadow-sm">
      <el-form :inline="true" :model="searchForm" class="flex flex-wrap">
        <el-form-item label="数据源名称">
          <el-input v-model="searchForm.name" placeholder="请输入数据源名称" clearable />
        </el-form-item>
        <el-form-item label="数据库类型">
          <el-select v-model="searchForm.type" placeholder="请选择数据库类型" clearable>
            <el-option v-for="item in dbTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="连接用户名">
          <el-input v-model="searchForm.username" placeholder="请输入连接用户名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" class="flex items-center">
            <div class="i-carbon-search mr-1"></div>查询
          </el-button>
          <el-button @click="handleReset" class="flex items-center">
            <div class="i-carbon-reset mr-1"></div>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表区 -->
    <el-card class="border-0 shadow-sm">
      <div class="flex justify-between mb-3">
        <div class="flex items-center">
          <div class="i-carbon-list-checked text-primary mr-2"></div>
          <span class="font-medium">数据源列表</span>
          <el-tag class="ml-2" type="info">总计 {{ total }} 条</el-tag>
        </div>
        <div>
          <el-button type="success" @click="handleImport" class="flex items-center">
            <div class="i-carbon-upload mr-1"></div>导入
          </el-button>
          <el-button type="info" @click="handleExport" class="flex items-center">
            <div class="i-carbon-download mr-1"></div>导出
          </el-button>
        </div>
      </div>

      <el-table v-loading="loading" :data="tableData" border style="width: 100%" row-key="id" class="mt-2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="数据源名称" min-width="150">
          <template #default="{ row }">
            <div class="flex items-center">
              <div :class="getDbTypeIcon(row.type)" class="mr-2 text-lg"></div>
              <span class="font-medium text-primary cursor-pointer" @click="handleView(row)">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="数据库类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getDbTypeTagType(row.type)">{{ getDbTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="连接URL" min-width="250" show-overflow-tooltip />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="schemaName" label="模式名/数据库" width="150" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'">
              {{ row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)" class="flex items-center">
              <div class="i-carbon-edit mr-1"></div>编辑
            </el-button>
            <el-button type="primary" link @click="handleTest(row)" class="flex items-center">
              <div class="i-carbon-settings-check mr-1"></div>测试连接
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleToggleStatus(row)"
              class="flex items-center"
            >
              <div :class="row.status === '1' ? 'i-carbon-power' : 'i-carbon-power-off'" class="mr-1"></div>
              {{ row.status === '1' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)" class="flex items-center">
              <div class="i-carbon-trash-can mr-1"></div>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 测试连接结果对话框 -->
    <el-dialog v-model="testDialogVisible" title="连接测试结果" width="500px">
      <div v-if="testLoading" class="flex flex-col items-center">
        <el-icon class="is-loading mb-4"><Loading /></el-icon>
        <span>正在测试连接，请稍候...</span>
      </div>
      <div v-else-if="testSuccess" class="flex flex-col items-center">
        <div class="i-carbon-checkmark-filled text-green-500 text-5xl mb-4"></div>
        <div class="text-lg font-medium">连接成功</div>
        <div class="text-gray-500 mt-2">数据源连接测试通过，可以正常使用</div>
      </div>
      <div v-else class="flex flex-col items-center">
        <div class="i-carbon-error-filled text-red-500 text-5xl mb-4"></div>
        <div class="text-lg font-medium">连接失败</div>
        <div class="text-gray-500 mt-2">{{ testErrorMessage }}</div>
      </div>
      <template #footer>
        <el-button @click="testDialogVisible = false">关闭</el-button>
        <el-button v-if="!testSuccess" type="primary" @click="handleRetryTest">重试</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据库类型选项
const dbTypeOptions = [
  { label: 'MySQL', value: 'MySQL' },
  { label: 'Oracle', value: 'Oracle' },
  { label: 'SQL Server', value: 'SQLServer' },
  { label: 'PostgreSQL', value: 'PostgreSQL' },
  { label: 'MongoDB', value: 'MongoDB' },
  { label: 'Redis', value: 'Redis' },
  { label: 'Hive', value: 'Hive' },
  { label: 'HBase', value: 'HBase' },
]

// 根据数据库类型获取图标
const getDbTypeIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    'MySQL': 'i-logos-mysql',
    'Oracle': 'i-logos-oracle',
    'SQLServer': 'i-logos-microsoft',
    'PostgreSQL': 'i-logos-postgresql',
    'MongoDB': 'i-logos-mongodb',
    'Redis': 'i-logos-redis',
    'Hive': 'i-logos-hadoop',
    'HBase': 'i-logos-hbase',
  }
  return iconMap[type] || 'i-carbon-data-base'
}

// 根据数据库类型获取标签类型
const getDbTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'MySQL': '',
    'Oracle': 'warning',
    'SQLServer': 'info',
    'PostgreSQL': 'success',
    'MongoDB': 'success',
    'Redis': 'danger',
    'Hive': 'warning',
    'HBase': 'info',
  }
  return typeMap[type] || ''
}

// 根据数据库类型获取标签文本
const getDbTypeLabel = (type: string) => {
  const typeLabel = dbTypeOptions.find(item => item.value === type)
  return typeLabel?.label || type
}

// 列表数据
const tableData = ref<any[]>([])
const loading = ref(false)
const total = ref(0)

// 搜索条件
const searchForm = reactive({
  name: '',
  type: '',
  username: '',
  status: '',
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
})

// 测试连接相关
const testDialogVisible = ref(false)
const testLoading = ref(false)
const testSuccess = ref(false)
const testErrorMessage = ref('')
const currentTestRow = ref<any>(null)

// 获取数据源列表
const getDataSourceList = () => {
  loading.value = true
  // 这里模拟接口请求
  setTimeout(() => {
    // 模拟数据
    const mockData = Array.from({ length: 25 }).map((_, index) => {
      const id = `ds_${index + 1}`
      const dbTypeIndex = index % dbTypeOptions.length
      const dbType = dbTypeOptions[dbTypeIndex].value
      const name = `${dbType}数据源${index + 1}`
      const url = getUrlByDbType(dbType, index)
      return {
        id,
        name,
        type: dbType,
        url,
        username: `user_${index + 1}`,
        password: '********',
        schemaName: getSchemaByDbType(dbType, index),
        owner: `owner_${index % 3}`,
        description: `${name}的描述信息`,
        status: index % 5 === 0 ? '0' : '1',
        createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toLocaleString(),
        createUser: 'admin',
        updateTime: new Date(Date.now() - Math.floor(Math.random() * 1000000000)).toLocaleString(),
        updateUser: 'admin',
      }
    })
    
    // 模拟搜索过滤
    let filteredData = [...mockData]
    if (searchForm.name) {
      filteredData = filteredData.filter(item => item.name.includes(searchForm.name))
    }
    if (searchForm.type) {
      filteredData = filteredData.filter(item => item.type === searchForm.type)
    }
    if (searchForm.username) {
      filteredData = filteredData.filter(item => item.username.includes(searchForm.username))
    }
    if (searchForm.status !== '') {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    // 模拟分页
    const start = (queryParams.pageNum - 1) * queryParams.pageSize
    const end = start + queryParams.pageSize
    const pageData = filteredData.slice(start, end)
    
    tableData.value = pageData
    total.value = filteredData.length
    loading.value = false
  }, 500)
}

// 根据数据库类型生成URL
const getUrlByDbType = (type: string, index: number) => {
  const urlMap: Record<string, string> = {
    'MySQL': `jdbc:mysql://db-server-${index % 5 + 1}.example.com:3306/db_${index + 1}`,
    'Oracle': `jdbc:oracle:thin:@oracle-server-${index % 3 + 1}.example.com:1521:orcl${index % 5}`,
    'SQLServer': `jdbc:sqlserver://sql-server-${index % 4 + 1}.example.com:1433;databaseName=db_${index + 1}`,
    'PostgreSQL': `jdbc:postgresql://pg-server-${index % 3 + 1}.example.com:5432/pg_${index + 1}`,
    'MongoDB': `mongodb://mongo-server-${index % 3 + 1}.example.com:27017/mongo_${index + 1}`,
    'Redis': `redis://redis-server-${index % 2 + 1}.example.com:6379/${index % 16}`,
    'Hive': `jdbc:hive2://hive-server-${index % 2 + 1}.example.com:10000/hive_${index + 1}`,
    'HBase': `hbase-server-${index % 2 + 1}.example.com:2181`,
  }
  return urlMap[type] || `jdbc:unknown://server-${index}.example.com`
}

// 根据数据库类型获取模式名
const getSchemaByDbType = (type: string, index: number) => {
  const schemaMap: Record<string, string> = {
    'MySQL': `db_${index + 1}`,
    'Oracle': `SCHEMA_${index % 5}`,
    'SQLServer': `dbo`,
    'PostgreSQL': `public`,
    'MongoDB': `mongo_${index + 1}`,
    'Redis': `${index % 16}`,
    'Hive': `default`,
    'HBase': `default`,
  }
  return schemaMap[type] || ''
}

// 搜索事件
const handleSearch = () => {
  queryParams.pageNum = 1
  getDataSourceList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = ''
  })
  queryParams.pageNum = 1
  getDataSourceList()
}

// 分页事件
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getDataSourceList()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getDataSourceList()
}

// 添加数据源
const handleAdd = () => {
  router.push({ path: '/metadata/DataSourceEdit' })
}

// 查看详情
const handleView = (row: any) => {
  router.push({ path: '/metadata/DataSourceEdit', query: { id: row.id, mode: 'view' } })
}

// 编辑数据源
const handleEdit = (row: any) => {
  router.push({ path: '/metadata/DataSourceEdit', query: { id: row.id, mode: 'edit' } })
}

// 测试连接
const handleTest = (row: any) => {
  testDialogVisible.value = true
  testLoading.value = true
  testSuccess.value = false
  testErrorMessage.value = ''
  currentTestRow.value = row
  
  // 模拟测试连接
  setTimeout(() => {
    testLoading.value = false
    // 随机测试结果，实际应该调用接口
    if (row.status === '1' && Math.random() > 0.2) {
      testSuccess.value = true
    } else {
      testSuccess.value = false
      if (row.status === '0') {
        testErrorMessage.value = '数据源已被禁用，无法连接'
      } else {
        const errors = [
          '连接超时，请检查网络或地址是否正确',
          '认证失败，请检查用户名和密码',
          '数据库不存在，请检查配置',
          '权限不足，无法建立连接',
          '驱动程序未找到，请检查配置'
        ]
        testErrorMessage.value = errors[Math.floor(Math.random() * errors.length)]
      }
    }
  }, 1500)
}

// 重试连接
const handleRetryTest = () => {
  if (currentTestRow.value) {
    handleTest(currentTestRow.value)
  }
}

// 切换状态
const handleToggleStatus = (row: any) => {
  const statusText = row.status === '1' ? '禁用' : '启用'
  ElMessageBox.confirm(
    `是否确认${statusText}数据源 "${row.name}"？`,
    `${statusText}确认`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 模拟接口调用
      setTimeout(() => {
        row.status = row.status === '1' ? '0' : '1'
        ElMessage({
          type: 'success',
          message: `${statusText}成功`,
        })
      }, 300)
    })
    .catch(() => {
      // 取消操作
    })
}

// 删除数据源
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除数据源 "${row.name}"？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 模拟删除操作
      setTimeout(() => {
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          tableData.value.splice(index, 1)
          total.value--
        }
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }, 300)
    })
    .catch(() => {
      // 取消删除
    })
}

// 导入数据源
const handleImport = () => {
  ElMessage({
    type: 'info',
    message: '导入功能开发中，敬请期待',
  })
}

// 导出数据源
const handleExport = () => {
  ElMessage({
    type: 'info',
    message: '导出功能开发中，敬请期待',
  })
}

// 初始化
onMounted(() => {
  getDataSourceList()
})
</script> 